import { Faction } from '../contexts/GameContext';

type UnitType = 'infantry' | 'cavalry' | 'archer' | 'artillery';

interface Unit {
  type: UnitType;
  attack: number;
  defense: number;
  health: number;
  cost: {
    grain: number;
    horses?: number;
    gunpowder?: number;
  };
  specialAbility?: () => void;
}

const UNIT_TYPES: Record<UnitType, Unit> = {
  infantry: {
    type: 'infantry',
    attack: 10,
    defense: 15,
    health: 100,
    cost: { grain: 20 }
  },
  cavalry: {
    type: 'cavalry',
    attack: 15,
    defense: 10,
    health: 80,
    cost: { grain: 15, horses: 10 }
  },
  archer: {
    type: 'archer',
    attack: 12,
    defense: 8,
    health: 70,
    cost: { grain: 10 }
  },
  artillery: {
    type: 'artillery',
    attack: 20,
    defense: 5,
    health: 50,
    cost: { grain: 25, gunpowder: 15 }
  }
};

const FACTION_BONUS: Record<string, (unit: Unit) => Unit> = {
  ming: (unit) => ({
    ...unit,
    defense: unit.defense + 3,
    health: unit.health + 10
  }),
  mongol: (unit) => ({
    ...unit,
    attack: unit.type === 'cavalry' ? unit.attack + 5 : unit.attack
  }),
  korea: (unit) => ({
    ...unit,
    attack: unit.type === 'archer' ? unit.attack + 4 : unit.attack
  }),
  japan: (unit) => ({
    ...unit,
    attack: unit.attack + 2 // 夜间加成在游戏逻辑中处理
  })
};

class BattleSystem {
  static createUnit(type: UnitType, faction: Faction): Unit {
    let unit = UNIT_TYPES[type];
    if (FACTION_BONUS[faction.id]) {
      unit = FACTION_BONUS[faction.id](unit);
    }
    return unit;
  }

  static calculateBattle(attacker: Unit, defender: Unit) {
    const attackPower = attacker.attack * (0.8 + Math.random() * 0.4);
    const defensePower = defender.defense * (0.8 + Math.random() * 0.4);
    
    if (attackPower > defensePower) {
      const damage = Math.max(1, Math.round(attackPower - defensePower));
      defender.health -= damage;
      return { winner: 'attacker', damage };
    } else {
      const damage = Math.max(1, Math.round(defensePower - attackPower));
      attacker.health -= damage;
      return { winner: 'defender', damage };
    }
  }

  static canAffordUnit(unit: Unit, resources: any) {
    return Object.entries(unit.cost).every(
      ([resource, amount]) => resources[resource] >= amount
    );
  }
}

export default BattleSystem;
